<!--  -->
<template>
  <div class='authority'>
    <el-button type="primary" v-permissions="'ranch:add'" @click="addRanch" style="margin-bottom: 10px;">新增</el-button>
    <el-form :inline="true" :model="formInRanch" class="demo-form-inline">
      <el-form-item label="牧场名称">
        <el-input v-model="formInRanch.ranchName" placeholder="请输入牧场名称" @change="enterKey"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        :data="getMyRanch"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="牧场名称"
          width="80">
        </el-table-column>
        <el-table-column
          prop="userName"
          label="联系人"
          width="100">
        </el-table-column>
        <el-table-column
          prop="userPhone"
          label="电话"
          width="120">
        </el-table-column>
        <el-table-column
          prop="address"
          label="具体位置"
          width="160">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          width="160">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          >
          <template slot-scope="scope">
            <el-button v-permissions="'ranch:detail'" @click="getRanchDetail(scope.row.id,scope.row.roleName)" type="text" size="small">详情</el-button>
            <!-- <el-button @click="setRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">修改</el-button> -->
            <el-button v-permissions="'ranch:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog
        title="牧场详情"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="true"
        width="50%">
        <el-form
          ref="ranchDetailsRefs"
          :model="updatedRanch"
          :disabled="isDisabled"
          :inline="false"
          class="demo-form-inline"
          label-position="left"
          :rules="ranchDetailsFrom"
          label-width="auto">
          <div class="filter-container">
            <el-form-item label="牧场名称" prop="name">
              <el-input v-model="updatedRanch.name"></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="userName">
              <el-input v-model="updatedRanch.userName"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="userPhone">
              <el-input v-model="updatedRanch.userPhone"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="detailsAddress">
              <el-cascader
                class="widthSmall"
                size="large"
                :options="options"
                v-model="updatedRanch.detailsAddress"
                @change="ChangeDetailsAddress">
              </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="addressPlot">
              <el-input v-model="updatedRanch.addressPlot" @input='myInputNotUpdate'></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="updatedRanch.remark"></el-input>
            </el-form-item>
          </div>
        </el-form>
        <div class="buttons">
           <el-button type="primary" v-permissions="'ranch:update'" @click="setConfigUserRole" v-if="isDisabled">修改</el-button>
           <el-button type="primary" @click="submitConfigUser" v-if="!isDisabled">保存</el-button>
           <el-button @click="closeDiaDetail">关闭</el-button>
        </div>
      </el-dialog>
      <!-- 新增 -->
      <el-dialog
        title="新增牧场"
        :visible.sync="addCompany"
        @close="closeDia"
        :close-on-press-escape="true"
        :close-on-click-modal="false"
        width="50%">
        <el-form ref="formName" :model="formAddRanch" :rules="addUserRule" label-width="80px">
          <el-form-item label="地址" prop="selectedOptions">
            <el-cascader
              class="widthSmall"
              size="large"
              :options="options"
              v-model="formAddRanch.selectedOptions"
              @change="addressChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input type="textarea" v-model="formAddRanch.address"></el-input>
          </el-form-item>
          <el-form-item label="牧场名称" prop="name">
            <el-input v-model="formAddRanch.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formAddRanch.phone"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formAddRanch.remark"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="userName">
            <el-input v-model="formAddRanch.userName"></el-input>
          </el-form-item>
        </el-form>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="addMyNewCompany">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getRanchListInit"
    />
  </div>
</template>

<script>
import { provinceAndCityData, CodeToText } from 'element-china-area-data'
import { ranchList, ranchAdd, ranchDtail, ranchUpdate } from '@/api/ranch'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    Pagination
  },
  data () {
    // 这里存放数据
    return {
      options: provinceAndCityData, // 省市区数据
      isDisabled: true,
      updatedRanch: { // 修改公司
        address: '',
        cityCode: '',
        companyId: '',
        expireTime: '',
        name: '',
        userPhone: '',
        userId: '',
        userName: '',
        detailsAddress: [],
        wordForDetailAddress: '',
        addressPlot: ''
      },
      getMyRanch: [], // 牧场列表
      formAddRanch: {
        name: '',
        phone: '',
        selectedOptions: [],
        address: '',
        cityProvince: '',
        cityCode: '',
        userName: '',
        remark: ''
      },
      // 修改详情 rule 验证
      ranchDetailsFrom: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        userPhone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ],
        addressPlot: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ],
        detailsAddress: [
          { required: true, trigger: 'change', message: '请选择地址' }
        ]
      },
      // 新增 rule 验证
      addUserRule: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ],
        address: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ],
        selectedOptions: [
          { required: true, trigger: 'change', message: '请选择地址' }
        ]
      },
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 查询
      formInRanch: {
        ranchName: ''
      },
      // checked: false,
      dialogVisible: false,
      userNameGet: '',
      userRoleIdGet: null,
      userRemarkGet: '',
      userList: JSON.parse(sessionStorage.getItem('routerList')),
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultCheckRole: [],
      setRoleIdArrFir: [],
      setRoleIdArrSen: [],
      addCompany: false
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 修改详情地址的时候不更新
    myInputNotUpdate () {
      this.$forceUpdate()
    },
    // 修改详情地址
    ChangeDetailsAddress (arr) {
      this.updatedRanch.detailsAddress = [arr[0], arr[1]]
      this.updatedRanch.wordForDetailAddress = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 地址选择 - 新增
    addressChange (arr) {
      this.formAddRanch.cityCode = arr[0] + '-' + arr[1]
      this.formAddRanch.cityProvince = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 获取牧场列表
    getRanchListInit () {
      ranchList({
        kw: this.formInRanch.ranchName,
        limit: this.pagination.pageSize,
        page: this.pagination.page
      }).then(res => {
        if (res.code === '200') {
          this.getMyRanch = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
            this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
            this.getRanchListInit()
          } else {
            this.pagination.total = res.data.total
          }
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
    },
    // 打开新增弹框
    addRanch () {
      this.addCompany = true
    },
    // 新增保存
    addMyNewCompany () {
      console.log(this.formAddRanch)
      const resAddressForAdd = this.formAddRanch.address === undefined ? '' : this.formAddRanch.address
      this.$refs.formName.validate((valid) => {
        if (valid) {
          this.formAddRanch.expireTime = new Date(this.formAddRanch.expireTime).getTime()
          const companyObj = {
            address: this.formAddRanch.cityProvince + '-' + resAddressForAdd,
            cityCode: this.formAddRanch.cityCode,
            name: this.formAddRanch.name,
            phone: this.formAddRanch.phone,
            userName: this.formAddRanch.userName,
            remark: this.formAddRanch.remark
          }
          console.log(companyObj)
          ranchAdd(companyObj).then(res => {
            this.addCompany = false
            if (res.code === '200') {
              this.getRanchListInit()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 查询
    submitSrearch () {
      this.getRanchListInit()
    },
    enterKey () {
      this.getRanchListInit()
    },
    // 重置
    resetForm () {
      this.formInRanch.ranchName = ''
    },
    // 删除用户
    deletRoleUser (val) {
      // this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //     center: true
      //   }).then(() => {
      //     companyDelete(val).then(res => {
      //       if (res.code === '200') {
      //         this.$message({
      //           message: '删除成功',
      //           type: 'success'
      //         })
      //         this.getRanchListInit()
      //       } else {
      //         this.$message({
      //           type: 'info',
      //           message: res,message
      //         });
      //       }
      //     })
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消删除'
      //     });
      //   });
    },
    // 用户详情
    getRanchDetail (val, name) {
      this.userNameGet = name
      this.userRoleIdGet = val
      ranchDtail(val).then(res => {
        this.updatedRanch = res.data
        this.updatedRanch.ranchId = res.data.id
        const start = this.updatedRanch.address.indexOf('-') + 1
        const detailEnd = this.updatedRanch.address.length
        const cityEnd = this.updatedRanch.cityCode.length
        const tagNum = this.updatedRanch.cityCode.indexOf('-')
        const provinceCode = this.updatedRanch.cityCode.substring(0, tagNum)
        const cityForCode = this.updatedRanch.cityCode.substring(tagNum + 1, cityEnd)
        this.updatedRanch.detailsAddress = [provinceCode, cityForCode]
        this.updatedRanch.wordForDetailAddress = CodeToText[provinceCode] + CodeToText[cityForCode]
        this.updatedRanch.addressPlot = this.updatedRanch.address.substring(start, detailEnd)
        this.dialogVisible = true
      })
    },
    // 修改用户详情
    setConfigUserRole () {
      this.$confirm('是否确认修改牧场信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisabled = false
        console.log(this.updatedRanch)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 保存修改后用户信息
    submitConfigUser () {
      this.$refs.ranchDetailsRefs.validate((valid) => {
        if (valid) {
          const resAddress = this.updatedRanch.addressPlot === undefined ? '' : this.updatedRanch.addressPlot
          const role = {
            address: this.updatedRanch.wordForDetailAddress + '-' + resAddress,
            cityCode: this.updatedRanch.detailsAddress[0] + '-' + this.updatedRanch.detailsAddress[1],
            name: this.updatedRanch.name,
            phone: this.updatedRanch.userPhone,
            ranchId: this.updatedRanch.ranchId,
            userName: this.updatedRanch.userName,
            remark: this.updatedRanch.remark
          }
          console.log(role, 458)
          ranchUpdate(role).then(res => {
            if (res.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.isDisabled = true
              this.getRanchListInit()
            } else {
              this.$message({
                type: 'info',
                message: res.message
              })
            }
          })
        }
      })
    },
    // 关闭新增弹框
    closeDia () {
      this.formAddRanch = {}
    },
    // 关闭详情弹框
    closeDiaDetail () {
      this.dialogVisible = false
      this.isDisabled = true
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getRanchListInit()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.fir {
  width: auto;
  height: 30px;
  line-height: 30px;
  span {
    margin-left: 10px;
    padding: 5px;
    width: 30%;
  }
}
.sen {
  margin: 5px auto;
  width: 80%;
  padding: 10px;
  border: 1px solid #f0f0f0;
}
.buttons {
  width: 100%;
  text-align: center;
}
</style>
